import serial
import serial.tools
import time

class Radio_Serial:
    def __init__(self):
        self.commands = {"AM":"40000", "FM":"2000"}
        self.band = "FM"
        self.station = 88.1
        self.port = 'COM3'
        self.setup()

    def setup(self, mode=None):
        not_done = True
        while not_done:    
            try:
                self.ser = serial.Serial(self.port, 9600)

            except:
                print "Connection unsuccessful. Please enter the serial port to connect to."
                self.port = raw_input("Port: ")

            else:
                not_done = False

        time.sleep(2)
        if mode:
            band = mode

        if self.band == 'FM':
            self.ser.write('2000226a\n')
        elif self.band == 'AM':
            self.ser.write('400003e8\n')
        elif self.band == 'SW':
            print "Not Implemented"
            return False
        elif self.band == 'LW':
            print "Not Implemented"
            return False
        else:
            return False
        return True

    def change_station(self, new_station):
        tmp_station = int(new_station * 100)
        tmp_station = hex(tmp_station)[2:]
        command = ''.join([commands[band], tmp_station, '\n'])
        ser.write(command)
        self.station = new_station

    def close():
        ser.close()
